import {
  axios_base_get
} from './axios.js'
const formatTime = (timestamp, format) => {
  timestamp = Number(timestamp)
  let date = new Date(timestamp);
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  if (format == 'YYYY-MM-DD') {
    return [year, month, day].map(formatNumber).join('-')
  }
  //时分
  else if (format == 'HH-MM') {
    return [hour, minute].map(formatNumber).join(':')
  } else {
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  }

}
const formatDateTime = (dateStr, format = 'yyyy-MM-dd HH:mm:ss') => {
  if (dateStr === '0001-01-01 00:00:00' || dateStr === '1900-01-01 00:00:00' || dateStr === '0001-01-01') return '';
  // 对Date的扩展，将 Date 转化为指定格式的String
  // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
  // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  // 例子：
  // (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
  // (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
  Date.prototype.Format = function (fmt) {
    var o = {
      'M+': this.getMonth() + 1, //月份
      'd+': this.getDate(), //日
      'H+': this.getHours(), //小时
      'm+': this.getMinutes(), //分
      's+': this.getSeconds(), //秒
      'q+': Math.floor((this.getMonth() + 3) / 3), //季度
      S: this.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
        );
    return fmt;
  };

  /** 格式化时间 */
  if (!dateStr || dateStr === '') return '';
  const date = new Date(dateStr.replace(/-/gi, '/'));
  return date.Format(format);
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//淡入淡出动画
const show = (that, param, opacity) => {
  var animation = wx.createAnimation({
    duration: 1500,
    timingFunction: 'ease',
  });
  animation.opacity(opacity).step()
  //将param转换为key
  var json = '{"' + param + '":""}'
  json = JSON.parse(json);
  json[param] = animation.export()
  //设置动画
  that.setData(json)
}

//高度从下到上
const showHeight = (that, param, height) => {
  var animation = wx.createAnimation({
    duration: 600,
    timingFunction: 'ease',
  });
  animation.height(height).step()
  var json = '{"' + param + '":""}'
  json = JSON.parse(json);
  json[param] = animation.export()
  that.setData(json)
}

//模块由下到上滑动
const slideupshow = (that, param, px, opacity) => {
  var animation = wx.createAnimation({
    duration: 500,
    timingFunction: 'ease'
  });
  animation.translateY(px).opacity(opacity).step()
  var json = {}
  json[param] = animation.export()
  that.setData(json)
}
//左右滑动渐入渐出
const sliderightshow = (that, param, px, opacity) => {
  var animation = wx.createAnimation({
    duration: 400,
    timingFunction: 'ease-end',
  });
  animation.translateX(px).opacity(opacity).step()
  var json = {}
  json[param] = animation.export()
  that.setData(json)
}
//X轴翻转动画
//css初始设置
//opacity: 0;
//transform: rotateX(90deg);
//-webkit - transform: rotateX(90deg); /* Safari and Chrome */

const sliderotateshow = (that, param, px, opacity) => {
  var animation = wx.createAnimation({
    duration: 1000,
    timingFunction: 'ease',
  });
  animation.rotateX(px).opacity(opacity).step()
  var json = {}
  json[param] = animation.export()
  that.setData(json)
}

//复制
const copyText = (text) => {
  wx.setClipboardData({
    data: text,
    success: function (res) {
      wx.showToast({
        title: '复制成功'
      });
    },
    fail: function (res) {
      wx.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  })
}

//二维码参数对象化
const getOptionsObj = (str) => {
  str = decodeURIComponent(str)
  let optionsList = str.split('&')
  let optionsObj = {}
  optionsList.forEach(item => {
    optionsObj[item.split('=')[0]] = item.split('=')[1]
  })
  return optionsObj
}
//扫一扫
const openScan = () => {
  wx.scanCode({
    success: (res) => {
      //有路径跳转
      let path = res.path;
      if (path) {
        if (path.substr(0, 1) != "/") {
          path = '/' + path
        }
        path = decodeURIComponent(path);
        const p = path.split('scene=');
        wx.reLaunch({
          url: p[0] + 'scene=' + encodeURIComponent(p[1])
        })
      } else if (res.result) {
        //判断以这些开头的，认定为凭证号
        let reg = /^[NCZX]/
        if (reg.test(res.result)) {
          wx.reLaunch({
            url: '/pages/base/scanInfo/scanInfo?type=voucher&code=' + res.result,
          })
        }
      }
    },
    fail: (res) => {
      wx.showToast({
        title: '扫描失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
/** 通过枚举值获取字典
 * @param enumName 枚举名称
 */
const getDicByEnumName = enumName => {
  if (enumName) {
    if (enumName === 'axBooleanType') {
      return [{
          text: '是',
          value: true,
        },
        {
          text: '否',
          value: false,
        },
      ];
    } else if (enumName === 'allBooleanType') {
      return [{
          text: '全部',
          value: '',
        },
        {
          text: '是',
          value: true,
        },
        {
          text: '否',
          value: false,
        }
      ];
    } else {
      let dic = wx.getStorageSync('keys');
      if (dic && dic.find) {
        const finder = dic.find(i => i.eName.toUpperCase() === enumName.toUpperCase());
        if (finder) return finder.dtoDictionaryValues;
      }
    }
  }
  return []
}

const getStandardList = (list, itemName = 'name', itemValue = 'id') => {
  let isArray = Array.isArray(list)
  if (isArray) {
    //暂时最多只接受两个元素数组,如['name','idcard']
    if (Array.isArray(itemName)) {
      if (itemName.length == 2) {
        list.forEach(item => {
          let str = ''
          if (item[itemName[1]]) str = '(' + item[itemName[1]] + ')'
          item.text = item[itemName[0]] + str
          item.value = item[itemValue]
        })
      }
    } else {
      list.forEach(item => {
        item.text = item[itemName]
        item.value = item[itemValue]
      })
    }
    return list
  }
  return []
}

/** 正则表达式验证 返回布尔值
 * @param val 需验证的值
 * @param regType 验证类型（empty,mobile,idcard）
 */
function valitorIdcard(num) {
  const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (reg.test(num) == true) {
    return true
  } else {
    return false
  }
}
const dataRegexp = async (val, regType) => {
  let mobileRegexp = /^1[3456789]\d{9}$/;
  let numberRegexp = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
  let idcardRegexp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  let idcardexRegexp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)|(^暂无身份证号码$)/;
  if (regType === 'empty') return !!(val === null || val === undefined || val === ""||(Array.isArray(val) && val.length === 0))
  if (regType === 'mobile') return mobileRegexp.test(val)
  if (regType === 'idcardRegexp') return idcardRegexp.test(val)
  if (regType === 'idcard') {
    if (idcardRegexp.test(val) === false) {
      return false;
    }
    //  else {
    //   return await axios_base_get('/Common/ValidateIdcard', {
    //     idcard: val
    //   }).then(res => {
    //     return res.data;
    //   });
    // }
  }
  if (regType === 'number') return numberRegexp.test(val)
  if (regType === 'idcardex') {
    if (idcardexRegexp.test(val) === false) {
      return false;
    } else if (val !== "暂无身份证号码") {
      return await axios_base_get('/Common/ValidateIdcard', {
        idcard: val
      }).then(res => {
        return res.data;
      });
    }
  }
  if (regType === 'bankcard') {
    return verifyBankCard(val);
  }
  return true
}
/**
 * 1. 拿出卡号最后一位的校验位后，从右至左，将卡号按位编码，从0开始，判断偶数或奇数
  2. 判断逻辑--对每一位的计算规则：如果这一位是奇数位，则返回值本身，如果是偶数位，先将值乘以2得到一个数n，如果n是一位数（小于10），直接返回n，否则将n的个位数和十位数相加返回。
  3. 从右向左遍历，对每一位字符执行上面的判断逻辑，并将每一位的计算结果相加得到一个总数sum。
  4. 如果sum+校验位能够整除10，则此号码有效，否则号码无效。
 * 
 */
function verifyBankCard(num) {
  num = num.toString().split(''); //变为字符串再转数组
  if (num.length > 19 || num.length < 15) return false; //银行卡号长度为15-19
  let lastNum = parseInt(num[num.length - 1]); //取出最后一位--校验位
  num.length = num.length - 1; //删除最后一个值
  num = num.reverse(); //变为数组再颠倒

  let sum = 0; //总数
  num.forEach((elem, i) => {
    elem = parseInt(elem);
    if (i % 2 === 0) {
      let n = elem * 2;
      if (n < 10) sum += n;
      else sum += (parseInt(n / 10) + n % 10);
    } else sum += elem;
  });
  return (sum + lastNum) % 10 === 0 ? true : false;
}
//获取枚举值text
const getEnumNameByValue = (name, value) => {
  let text = ''
  if (name == 'axBooleanType') {
    if (value == true || value == 'true') text = '是'
    if (value == false || value == 'false') text = '否'
  } else {
    let keyList = wx.getStorageSync("keys")
    const obj = keyList && keyList.find(i => i.eName.toUpperCase() == name.toUpperCase());
    if (obj) {
      let key = obj.dtoDictionaryValues.find(i => i.value == value)
      if (key) text = key.text
    }
  }
  return text
}
const getAreaFullName = (key, treeData) => {
  const loops = (list) => {
    const len = list.length;
    for (let i = 0; i < len; i++) {
      const item = list[i];
      if (key == item.code) {
        return item.text;
      }
      const children = item.children;
      if (Array.isArray(children)) {
        const txt = loops(children);
        if (txt) {
          return item.text + txt;
        }
      }
    }
  };
  return loops(treeData);
};


/* 
fn : 回调函数  传进来的是正真的业务逻辑
delay : 延时时间
*/
function debounce(fn, delay = 3000) {
  let time = null; //time用来控制事件的触发
  return function () {
    if (time !== null) {
      clearTimeout(time);
    }
    time = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay)
  }
}

/**
 * 从数组数据集中过滤数据
 * @param {*} arr 数据数组
 * @param {*} key 要获取的数据的key
 * @param {*} filter 过滤条件
 */
function getDataFromDataSet(arr, key, filter) {
  const a = [];
  // 获取所有数据
  arr.forEach(i => {
    a.push(...i[key]);
  });

  // 去重
  let s = [...new Set(a.map(i => JSON.stringify(i)))].map(i => JSON.parse(i));

  if (Array.isArray(filter)) {
    // 有过滤条件，数据全部先设置为无效
    s = s.map(i => ({
      ...i,
      disabled: true,
    }));

    let f = arr;

    // 过滤数据
    filter.forEach(i => {
      if (i.value) {
        f = f.filter(j => j[i.key].find(k => k.value == i.value));
      }
    });

    // 获取有效数据
    const ga = getDataFromDataSet(f, key);

    // 重新生成数据
    s.forEach(i => {
      if (ga.find(j => j.value == i.value)) {
        i.disabled = false;
      }
    })

    return s;
  }

  // 没有过滤条件，数据全部有效
  return s.map(i => ({
    ...i,
    disabled: false,
  }));
}

/**
 * 判断值在数组中是否有效
 * @param {*} arr 数组
 * @param {*} val 值
 */
function isValidValue(arr, val) {
  if (arr.find(i => i.value == val && i.disabled !== true)) {
    return val;
  }

  return null;
}

/**
 * 从数组数据集中获取最终的数据
 * @param {*} arr 数组
 * @param {*} filter 过滤条件
 */
function getFinalDataFromDataSet(arr, filter, valid = true) {
  if (Array.isArray(filter)) {

    const validArr = arr.map(i => {
      const b = filter.some(j => {
        if (j.value) {
          if (!i[j.key].find(k => k.value == j.value)) {
            return true;
          }
        }

        return false;
      });

      return {
        ...i,
        disabled: b,
      };
    });

    if (valid) {
      return validArr.filter(i => i.disabled === false);
    }

    return validArr;
  }

  return arr.map(i => ({
    ...i,
    disabled: false,
  }));
}
/** 转换后端传回来的表单字段的配置信息
 * @params fields 字段
 */
const transformFields = (fields, groupName, groupId) => {
  const f = {};
  fields && Array.isArray(fields) && fields.forEach(i => {
    if (i.isShow === false) {
      return;
    }
    let info = i.selectValue,
      columnsFromConfig = [];

    if (info) {
      columnsFromConfig = info.split(',').map(j => ({
        text: j,
        value: j
      }));
    }
    let fileImageList =''
    let value=''
    if (i.boxType == 11 || i.boxType == 10) {
      fileImageList = []
    }
    f[i.eName] = {
      label: i.name,
      required: i.isRequired,
      isShow: i.isShow,
      // placeholder: i.remark,
      pattern: i.pattern || '',
      columnsFromConfig,
      groupName,
      groupId,
      fileImageList,
      value,
      ...i
    };
  });

  return f;
}

/** 转换后端传回来的表单字段
 * @params fields 字段
 */
const transformFormFields = (fields) => {
  const f = [];
  fields && Array.isArray(fields) && fields.forEach(i => {
    if (i.isShow === false) {
      return;
    }

    let info = i.info,
      columnsFromConfig = [];

    if (info) {
      columnsFromConfig = info.split(',').map(j => ({
        text: j,
        value: j
      }));
    }
    f.push({
      type: i.boxType,
      name: i.eName,
      fileQty: i.fileQty,
      templateUrl: i.templateUrl,
    });
  });

  return f;
}
module.exports = {
  transformFields,
  transformFormFields,
  formatTime,
  formatDateTime,
  show,
  showHeight,
  slideupshow,
  sliderightshow,
  sliderotateshow,
  copyText,
  getOptionsObj,
  openScan,
  getDicByEnumName,
  getEnumNameByValue,
  getStandardList,
  dataRegexp,
  getAreaFullName,
  debounce,
  getDataFromDataSet,
  isValidValue,
  getFinalDataFromDataSet,
  valitorIdcard
}